import 'dart:async';

import 'package:app_links/app_links.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_binding.dart';
import 'package:flutter_taotaoshipin/common/theme/app_theme.dart';
import 'package:flutter_taotaoshipin/common/translations/app_translations.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/apple_pay_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late AppLinks _appLinks;
  StreamSubscription<Uri>? _linkSubscription;

  @override
  void initState() {
    super.initState();
    // 添加苹果监听
    applePayUtils.startSubscription();
    // 深度链接
    initDeepLinks();
  }

  @override
  void dispose() {
    _linkSubscription?.cancel();
    super.dispose();
  }

  Future<void> initDeepLinks() async {
    _appLinks = AppLinks();

    // Check initial link if app was in cold state (terminated)
    final appLink = await _appLinks.getInitialAppLink();
    if (appLink != null) {
      print('冷启动: $appLink');
      openAppLink(appLink);
    }

    // Handle link when app is in warm state (front or background)
    _linkSubscription = _appLinks.uriLinkStream.listen((uri) {
      print('热启动: $uri');
      openAppLink(uri);
    });
  }

  void openAppLink(Uri uri) {}

  @override
  Widget build(BuildContext context) {
    var app = ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_, child) => GetMaterialApp(
        title: '考拉好剧'.tr,
        // showPerformanceOverlay: true, //显示性能标签
        debugShowCheckedModeBanner: false, // 去除右上角debug的标签
        // checkerboardRasterCacheImages: true,
        // showSemanticsDebugger: true, // 显示语义视图
        // checkerboardOffscreenLayers: true, // 检查离屏渲染
        // 国际化
        locale: AppTranslations.locale(),
        fallbackLocale: AppTranslations.fallbackLocale(),
        translations: AppTranslations(),
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: [
          const Locale('zh', 'CN'),
          const Locale('en', 'US'),
        ],
        // 页面切换动画
        defaultTransition: Transition.native,
        // 路由
        initialRoute: AppRoutes.init,
        getPages: AppRoutes.routes,
        unknownRoute: AppRoutes.unknownRoute,
        // 主题
        theme: AppTheme.getTheme(),
        // darkTheme: AppTheme.getTheme(isDarkMode: true),
        // themeMode: AppTheme.getThemeMode(),
        builder: EasyLoading.init(
          builder: (context, child) {
            /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
              child: child!,
            );
          },
        ),
        // 初始化绑定
        initialBinding: AppBinding(),
      ),
    );

    return app;
  }
}
